package com.hc.likelistenmusic.fragment

import android.view.View
import android.view.View.VISIBLE
import android.widget.SeekBar
import android.widget.TextView
import com.google.gson.Gson
import com.hc.likelistenmusic.R
import com.hc.likelistenmusic.activity.OnlineMusicActivity
import com.hc.likelistenmusic.bean.OnlineMusicLrcResponse
import com.hc.likelistenmusic.util.LrcUtil
import com.hc.likelistenmusic.util.OkHttpUtil
import com.hc.likelistenmusic.util.OkHttpUtil.ResultCallback
import com.hc.likelistenmusic.view.LrcView
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File
import java.io.FileOutputStream

class OnlineLrcFragment : LazyFragment(false) {
    lateinit var mLv_fol:LrcView
    lateinit var mSb_fol:SeekBar
    lateinit var mTv_fol_empty_lrc:TextView
    lateinit var mOnlineMusicActivity: OnlineMusicActivity
    override fun initView(rootView: View) {
        mOnlineMusicActivity = activity as OnlineMusicActivity
        mLv_fol = rootView.findViewById(R.id.lv_fol)
        mSb_fol = rootView.findViewById(R.id.sb_fol)
        mTv_fol_empty_lrc = rootView.findViewById(R.id.tv_fol_empty_lrc)

        mSb_fol.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {

            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {

            }

            override fun onStopTrackingTouch(seekBar: SeekBar) {
                if (mOnlineMusicActivity.onSeletedMusicId()) {
                    mLv_fol.updateCurrentLine(seekBar.progress)
                    mOnlineMusicActivity.handSyncProgress(seekBar.progress)
                } else {
                    seekBar.progress = 0
                }
            }
        })
        mLv_fol.setOnApplyIndicatorLineListener { time, lrc ->
            handSyncLrcProgress(time)
        }
    }

    override fun getLayoutResId(): Int {
        return R.layout.fragment_online_lrc
    }

    fun setNoLrcs() {
        mLv_fol.setLrcs(null)
        mLv_fol.pauseAutoScroll()
        mLv_fol.visibility = View.GONE
        mTv_fol_empty_lrc.visibility = VISIBLE
    }

    fun handSyncLrcProgress(currentProgress: Int) {
        mLv_fol.updateCurrentLine(currentProgress)
        mOnlineMusicActivity.handSyncProgress(currentProgress)
    }

    fun loadLrcData(id: Int) {
        OkHttpUtil.getInstance().requestWithParams("http://music.163.com/api/song/lyric?os=pc&id=${id}&lv=-1&kv=-1&tv=-1",true,false,null,null,object :ResultCallback{
            override fun onFailure(message: String) {
                CoroutineScope(Dispatchers.Main).launch {
                    setNoLrcs()
                }
            }

            override fun onResponseFailure(failureCode: Int, info: String) {
                CoroutineScope(Dispatchers.Main).launch {
                    setNoLrcs()
                }
            }

            override fun onResponseSuccess(successCode: Int, info: String) {
                try {
                    val gson = Gson()
                    val onlineMusicLrcResponse = gson.fromJson(info, OnlineMusicLrcResponse::class.java)
                    var file = File(mOnlineMusicActivity.cacheDir,"cache_lrc_${id}")
                    val fos = FileOutputStream(file)
                    fos.write(onlineMusicLrcResponse.lrc.lyric.toByteArray())
                    val lrcs = LrcUtil.analysisLrcFromFile(file)
                    if (lrcs.isNullOrEmpty()) {
                        mLv_fol.pauseAutoScroll()
                        CoroutineScope(Dispatchers.Main).launch {
                            mTv_fol_empty_lrc.visibility = VISIBLE
                            mLv_fol.visibility = View.GONE
                        }
                    } else {
                        mLv_fol.resumeAutoScroll()
                        CoroutineScope(Dispatchers.Main).launch{
                            mTv_fol_empty_lrc.visibility = View.GONE
                            mLv_fol.visibility = VISIBLE
                        }
                    }
                    mLv_fol.setLrcs(lrcs)
                    file.delete()
                }catch (e:Exception){
                    e.printStackTrace()
                    CoroutineScope(Dispatchers.Main).launch {
                        setNoLrcs()
                    }
                }
            }
        })
    }

    fun onProgress(current: Int, total: Int) {
        if(current==0){
            mSb_fol.max = total
        }
        mSb_fol.progress = current
        mLv_fol.updateCurrentLine(current)
    }
}